import logging
import os
import threading
import time

import openpyxl
from PyQt5.QtCore import QThread, pyqtSignal

wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Data"

data_type = ['PartNumber','DateTime','Result','Raum-Temperatur', 'Barometer', 'NT2 KMA-URef R2', 'NT3 Regler', 'NT4 Druckmesser', 'NT5 Last', 'Unterdruck (UMA)','Durchfluss (UMA)']

def title_1():
    column_names = data_type
    for col_idx, col_name in enumerate(column_names, start=1):
        ws.cell(row=1, column=col_idx, value=col_name)
        # ws_2.cell(row=1, column=col_idx, value=col_name)
    logging.info('Write down the title')

def read_txt_file(file_path):
    try:
        with open(file_path, 'r') as f:
            return f.readlines()
    except FileNotFoundError:
        logging.error(f"File not found: {file_path}")
        return None

class S118ConvertWorker(QThread):
    statusMessage = pyqtSignal(str)
    def __init__(self, files_path):
        super().__init__()
        self.files_path = files_path


    def read_S118_data(self,file_path):
        lines = read_txt_file(file_path)
        if lines[26]:
            PartNumber = lines[26].split()[0]
        DateTime = lines[32].split()[0]
        Result = lines[28].split()[0]
        Raum_Temperatur = ''
        Barometer = ''
        NT2_KMA_URef = ''
        NT3_Regler = ''
        NT4_Druckmesser = ''
        NT5_Last = ''
        Unterdruck_UMA = ''
        Durchfluss_UMA = ''
        if 'Raum-Temperatur' in lines[3]:
            Raum_Temperatur = float(lines[3].split()[1])
        if 'Barometer' in lines[5]:
            Barometer = float(lines[5].split()[1])

        if 'NT2 KMA-URef R2' in lines[7]:
            NT2_KMA_URef = float(lines[7].split()[3])

        if 'NT3 Regler' in lines[9]:
            NT3_Regler= float(lines[9].split()[2])

        if 'NT4 Druckmesser' in lines[11]:
            NT4_Druckmesser = float(lines[11].split()[2])

        if 'NT5 Last' in lines[13]:
            NT5_Last = float(lines[13].split()[2])

        if 'Unterdruck (UMA)' in lines[19]:
            Unterdruck_UMA =float( lines[19].split()[2])

        if 'Durchfluss (UMA)' in lines[21]:
            Durchfluss_UMA = float(lines[21].split()[2])
        return PartNumber, DateTime, Result,Raum_Temperatur, Barometer, NT2_KMA_URef, NT3_Regler, NT4_Druckmesser, NT5_Last, Unterdruck_UMA, Durchfluss_UMA


    def process_file(self,file_name):
        file_path = os.path.join(self.files_path, file_name)
        data = self.read_S118_data(file_path)
        ws.append(data)

    def get_file_names(self,directory):
        return [f for f in os.listdir(directory) if f.endswith('.log')]



    # read_S118_data(r'D:\ForPythonTes\ReadCalibrationTestReport\rek-118\0191892300002403270511_AAA9189230000_240327141501_TestProtokoll.log')
    def run(self):
        try :
            title_1()
            self.statusMessage.emit('Reading files...')
            file_names = self.get_file_names(self.files_path)
            self.statusMessage.emit(f'There are {len(self.get_file_names(self.files_path))} files in the folder.')

            threads = []
            for file_name in file_names:
                print(f'Processing file: {file_name}')
                self.statusMessage.emit(f'Processing file: {file_name}')
                t = threading.Thread(target=self.process_file, args=(file_name,))
                threads.append(t)
                t.start()

            for t in threads:
                t.join()
            excel_name = f'S118_data{time.strftime("%Y%m%d%H%M%S")}.xlsx'
            wb.save(os.path.join(self.files_path,excel_name))
            self.statusMessage.emit('Conversion completed!')
            self.statusMessage.emit(f'Excel would save here:{self.files_path}')

        except Exception as e:
            logging.error(f"An error occurred: {e}")
            self.statusMessage.emit(f'An error occurred :{str(e)}')

# if __name__ == '__main__':
#     main()